const express = require('express')
const cors = require('cors')
const helmet = require('helmet')
const morgan = require('morgan')
const path = require('path')
require('dotenv').config()

const app = express()

// 中间件
app.use(helmet())
app.use(cors())
app.use(morgan('combined'))
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true, limit: '10mb' }))

// 静态文件
app.use('/uploads', express.static(path.join(__dirname, '../uploads')))

// 路由
app.use('/api/auth', require('./routes/auth'))
app.use('/api/users', require('./routes/users'))
app.use('/api/products', require('./routes/products'))
app.use('/api/orders', require('./routes/orders'))
app.use('/api/inventory', require('./routes/inventory'))
app.use('/api/members', require('./routes/members'))
app.use('/api/marketing', require('./routes/marketing'))
app.use('/api/distribution', require('./routes/distribution'))
app.use('/api/shop', require('./routes/shop'))
app.use('/api/stores', require('./routes/stores'))
app.use('/api/statistics', require('./routes/statistics'))
app.use('/api/analytics', require('./routes/analytics'))
app.use('/api/system', require('./routes/system'))
app.use('/api/config', require('./routes/config'))

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() })
})

// 404处理
app.use((req, res) => {
  res.status(404).json({
    code: 404,
    message: '接口不存在',
    path: req.originalUrl
  })
})

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).json({
    code: 500,
    message: err.message || '服务器内部错误'
  })
})

const PORT = process.env.PORT || 3001

app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`)
  console.log(`API文档: http://localhost:${PORT}/api-docs`)
})
